import * as Ladda from './ladda.js';

$(function(){
	/*value：表示当前单元格中的值
	row：表示当前行
	index：表示当前行的下标*/
	function operateFormatter(value, row, index) {
	    return [
	    	'<button class="btn btn-danger update" data-toggle="modal" data-target="#editModal">更新</button>  ',
			'<button class="btn btn-danger remove" data-toggle="modal" data-target="#confirmModal">删除</button>'
	    ].join('')
	}

	//当值为0或null时显示无
	function CustomFormatter(value, row, index){
		if(value == 0 || value == null){
			return '无';
		}else{
			return value;
		}
	}

	//表格操作
	window.operateEvents = {
		//修改
		'click .update': function (e, value, row, index) {
			console.log(row);
			if(row.user.account == ''||row.user.account == null){
				row.user.account = '无';
			}
			$(".input-name").val(row.user.account);
			$("#editModal .input-version").val(row.version);
			$("input:hidden[id='updateId']").val(row.id);
		},
		    
		//删除
		'click .remove': function (e, value, row, index) {
			$("input:hidden[id='deleteId']").val(row.id);
			$("#confirmModalMessage").text("确认删除?");
		}
	}

	//bootstrap-table配置
	$('#firmware-tab').bootstrapTable({
	    url: '/firmware/fingPage',
	    toolbar: "#firmware-toolbar",
	    toolbarAlign:'right',
	    sidePagination: "server",
	    striped: true, // 是否显示行间隔色
	    pageNumber : 1, 
	    pageSize: 8,
	    pageList: [8, 25],
	    pagination: true, // 是否分页
	    sortable: true, // 是否启用排序
	    queryParams: function(params) {//上传服务器的参数
	        var temp = {
	        	pageNum : this.pageNumber,  
	        	pageSize : this.pageSize,
	        	userName : $("#searchName").val()
	        };
	        return temp;
	    },
	    columns: [{
	            field: 'user.account',
	            title: '客户账号',
	            formatter: CustomFormatter
	        },
	        {
	            field: 'version',
	            title: '版本号',
	            formatter: CustomFormatter
	        },
	        {
	            field: 'md5',
	            title: 'md5',
	            formatter: CustomFormatter
	        },
	        {
	            field: 'url',
	            title: '固件包下载地址',
	            formatter: CustomFormatter
	        },
	        {
	            field: '',
	            title: '操作',
	            align: 'center',
	            valign: 'middle',
	            formatter: operateFormatter,
	            events: window.operateEvents
	        },

	    ]
	});
	
	//查询
	$(document).on('click', "#searchBtn",function(){
	     $('#firmware-tab').bootstrapTable('selectPage', 1, 'refresh');
	     $('#searchModal').modal('hide');
	});

	//固件包版本号是数字
	$('.input-version').keyup(function(){
		var value = $(this).val();
		$(this).val(value.replace(/[^\d]/g,''))
	})


	//获取内容商
	var selectData = [];

	$.ajax({url:"/user/query",async: false,success:function(result){
		var _data = $.map(result.data.users, function (obj) {
			obj.text = obj.text || obj.account; 
			return obj;
		});
		selectData = _data
	}});

	//开启select2
	$('.js-data-example-ajax').select2({
		data: selectData
	});
	
	// 定义jQuery 自己的 XMLHttpRequest 对象，停止上传调用
	var jqXHR;
	//新建固件包
	$("#fileupload").fileupload({
		type : "POST",
		url : "/firmware/insert",
		autoUpload: false,
	    maxNumberOfFiles : 1,
	    add: function (ev, data) {
	    	$("#uploadBtn").off("click").click(function () {
	    		data.formData = {
	    			id: $("#select2").select2("data")[0].id,
	    			account: $("#select2").select2("data")[0].account,
	    			version: $("#versionInput").val()
	    		}
	    		$("#uploadBtn").css('display','none');
				$("#cancelBtn").css('display','block');
				jqXHR = data.submit();
	        });
	    	$("#cancelBtn").off("click").click(function () {
	    		jqXHR.abort();
	    		$(".progress").css('display','none');
				$("#cancelBtn").css('display','none');
				$("#uploadBtn").text("确定上传");
		    	$("#uploadBtn").css('display','block');
	        });
	    },
	    progressall: function(e, data) {
			var progress = parseInt(data.loaded / data.total * 100, 10);
			$(".progress").css('display','block');
			$(".progress-bar").css('width',progress+'%');
			if(progress == 100){
				$(".progress").css('display','none');
				$("#cancelBtn").css('display','none');
				$("#uploadBtn").text("确定上传");
		    	$("#uploadBtn").css('display','block');
		    	$("#uploadBtn").attr({ disabled: "disabled" });
			}
		},
	    done: function (e, data) {
	    	$("#uploadBtn").removeAttr("disabled");
	    	console.log(data);
	    	if(data._response.result.code == 0){
	    		window.location.reload()//刷新当前页面
	    	}else{
	    		alert("上传失败，" + data._response.result.message);
	    	}
	    },
	    fail: function (e, data) {
	    	$("#uploadBtn").removeAttr("disabled");
	    	if (data.errorThrown=='abort') {
	    		$("#newModal").modal("toggle");
	    		$("#cancelModal").modal("toggle");
	        }else{
	        	alert("上传资源失败,请检查");
	        }
	    }
	})
	
	//更新固件包
	$("#fileupdate").fileupload({
		type: "post",
		url: "/firmware/update",
		autoUpload: false,
	    maxNumberOfFiles : 1,
	    add: function(ev, data){
	    	$("#updateBtn").off("click").click(function(){
	    		data.formData = {
	    			id: $("input:hidden[id='updateId']").val(),
	    			version: $("#versionUpdate").val(),
	    			account: $(".input-name").val()
	    		}
	    		$("#updateBtn").css('display','none');
				$("#cancelupdateBtn").css('display','block');
				jqXHR = data.submit();
	    	})
	    	$("#cancelupdateBtn").off("click").click(function () {
	    		jqXHR.abort();
	    		$(".progress").css('display','none');
				$("#cancelupdateBtn").css('display','none');
				$("#updateBtn").text("确定上传");
		    	$("#updateBtn").css('display','block');
	        });
	    },
	    progressall: function(e, data) {
			var progress = parseInt(data.loaded / data.total * 100, 10);
			$(".progress").css('display','block');
			$(".progress-bar").css('width',progress+'%');
			if(progress == 100){
				$(".progress").css('display','none');
				$("#cancelupdateBtn").css('display','none');
				$("#updateBtn").text("确定上传");
		    	$("#updateBtn").css('display','block');
		    	$("#updateBtn").attr({ disabled: "disabled" });
			}
		},
	    done: function (e, data) {
	    	$("#updateBtn").removeAttr("disabled");
	    	
	    	if(data._response.result.code == 0){
	    		window.location.reload()//刷新当前页面
	    	}else{
	    		alert("更新失败，"+data._response.result.message);
	    	}
			
	    },
	    fail: function (e, data) {
	    	$("#updateBtn").removeAttr("disabled");
	    	if (data.errorThrown=='abort') {
	    		$("#editModal").modal("toggle");
	    		$("#cancelModal").modal("toggle");
	        }else{
	        	alert("更新资源失败,请检查");
	        }
	    }
	})
	
	//删除固件包
	$("#btn-delete").click(function(){
		var firmwareId = $("input:hidden[id='deleteId']").val();
		var l = Ladda.create(this);
		
		$.ajax({
			type: "post",
			url: "/firmware/delete",
			data: {id: firmwareId},
			beforeSend: function () {
		 		$(".ladda-delete").text("正在请求服务器");
		 	 	l.start();
		    },
		    complete: function () {
		    	$(".ladda-delete").text("删除");
		    	l.stop();
		    },
			success: function(result){
				if(result.code == 0){
					window.location.reload()//刷新当前页面
				}else{
					alert("删除资源失败,请检查");
				}
			}
		})
	})
	
})
